import os
import logging
import time

import requests
import threading
from flask import Flask, request
from flask_cors import CORS
from util import path, msg_manage, get_repo_info
from util import get_single_package_source_info
from util.common_utils import resp_json
import session_manage

# msg_man = msg_manage.MsgQueue()
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(message)s', datefmt='%Y/%m/%d %H:%M:%S')
app = Flask(__name__)

config = {
    "master_link": "http://192.168.31.52:9999",
    "api_name": "兼容性报告生成",
    "api_link": "http://192.168.31.52:9998/",
    "api_type": "POST",
    "api_scope": "compatibility_report_generate",
    "api_single_str": "compatibility_report_generate_20230118",
    "api_params": {},
    "api_icon": "https://images.onlinelabels.com/images/clip-art/chovynz/chovynz_Orange_Icon.png",
    "server_compatibility_report_generate": {
        "host": "192.168.206.129",
        "username": "root",
        "password": "qwer2850.",
        "script_run_str": "ls\nls\nls"
    }
}


@app.route('/heart', methods=['get', 'post'])
def heart():
    return resp_json(msg="agent启动成功！")


@app.route('/get_info', methods=['get', 'post'])
def get_info():
    return resp_json(msg="获取信息！", data=config)


@app.route('/run_task', methods=['get', 'post'])
def run_task():
    return resp_json(msg="执行任务！")


@app.route('/get_status', methods=['get', 'post'])
def get_status():
    return resp_json(msg="获取状态！")


@app.route('/run_clear', methods=['get', 'post'])
def run_clear():
    return resp_json(msg="清除任务！")


def agent_register():
    print('agent正在启动中...')
    while True:  # 死循环，监听服务启动情况，启动成功后跳出
        try:
            requests.post(url=config.get("api_link").rstrip('/') + "/heart")
            break
        except Exception as e:
            print(e)
            time.sleep(3)
    print('agent启动成功！')
    while True:  # 注册到Master，并每过固定时间重新注册一次，避免Master重启后数据丢失
        try:  # 启动成功后的回调
            res = requests.post(url=config.get("master_link").rstrip('/') + "/agent_register",
                                json={"agent_link": config.get("api_link")})
            print("注册成功，", res.text)
        except Exception as e:
            print("注册失败，失败原因：", e)
            # exit()
        time.sleep(10)


CORS(app, resources=r'/*')
if __name__ == "__main__":
    threading.Thread(target=agent_register).start()
    app.run(debug=True, host='0.0.0.0', port=9998)  # 运行app
